Data Cleaning and Understanding: Graphs with removed outliers

car0 <- read.csv("all_cars.csv")
car1 <- read.csv("cars_years.csv")
car2 <- read.csv("cars.csv")
car0$X <- NULL
car <- rbind(car0,car1,car2)
nrow(car)
## [1] 126823
cars <- unique(car)
nrow(cars)
## [1] 57341
# from 126823 data points to 57341
# this can be explained that the first scraping attempts had some looping errors and so sometimes the same cars got scraped. Another reason is, that the autoscout algorithm sometime showed the same cars.

#now let's have a look how the uncleaned dataset looks like: 
head(cars)
##              name      marke modell       preis karosserie   zustand zulassung
## 1      Opel Corsa       Opel  Corsa \n\200 299,-\n  Limousine Gebraucht      2000
## 2     Ford Fiesta       Ford Fiesta \n\200 499,-\n Kleinwagen Gebraucht      2000
## 3       Mazda 323      Mazda    323 \n\200 650,-\n  Limousine Gebraucht      2000
## 4  Renault Scenic    Renault Scenic \n\200 950,-\n      Kombi Gebraucht      2000
## 5         Audi A3       Audi     A3 \n\200 950,-\n  Limousine Gebraucht      2000
## 6 Volkswagen Golf Volkswagen   Golf \n\200 999,-\n  Limousine Gebraucht      2000
##     farbe tueren   hubraum sitzplätze           fahrzeughalter
## 1    Blau      2 1.199 cm³          5     \n3 Fahrzeughalter\n
## 2    Blau      3 1.242 cm³          5     \n3 Fahrzeughalter\n
## 3     Rot      5 1.489 cm³         NA     \n2 Fahrzeughalter\n
## 4     Rot      4 1.598 cm³          5 \n-/- (Fahrzeughalter)\n
## 5  Silber      5 1.595 cm³          5     \n3 Fahrzeughalter\n
## 6 Schwarz      3 1.390 cm³          5 \n-/- (Fahrzeughalter)\n
##             getriebe                 ps             km kraftstoff
## 1 \nSchaltgetriebe\n  \n48 kW (65 PS)\n \n126.000 km\n \nBenzin\n
## 2 \nSchaltgetriebe\n  \n55 kW (75 PS)\n \n189.137 km\n \nBenzin\n
## 3 \nSchaltgetriebe\n  \n65 kW (88 PS)\n \n168.000 km\n \nBenzin\n
## 4 \nSchaltgetriebe\n \n79 kW (107 PS)\n \n175.778 km\n \nBenzin\n
## 5 \nSchaltgetriebe\n \n74 kW (101 PS)\n \n230.800 km\n \nBenzin\n
## 6 \nSchaltgetriebe\n  \n55 kW (75 PS)\n \n245.000 km\n \nBenzin\n
##                                                                                                                                                                                                                                                                                                                                                                                                                             co2
## 1 \n151 g CO2/km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
## 2                                                                                                                                                                                                                                                                                                                                                                                                              \n-/- (CO2/km)\n
## 3   \n0 g CO2/km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
## 4 \n180 g CO2/km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
## 5 \n187 g CO2/km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
## 6 \n158 g CO2/km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
##                                                                                                                                                                                                                                                                                                                                                                                                                       verbrauch
## 1 \n6,3 l/100 km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
## 2                                                                                                                                                                                                                                                                                                                                                                                                            \n-/- (l/100 km)\n
## 3                                                                                                                                                                                                                                                                                                                                                                                                            \n-/- (l/100 km)\n
## 4 \n9,6 l/100 km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
## 5 \n7,8 l/100 km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
## 6 \n6,6 l/100 km (komb)\nWeitere Informationen zum offiziellen Kraftstoffverbrauch und den offiziellen spezifischen CO2-Emissionen neuer Personenkraftwagen können dem "Leitfaden über den Kraftstoffverbrauch, die CO2-Emissionen und den Stromverbrauch neuer Personenkraftwagen" entnommen werden, der an allen Verkaufsstellen und bei der Deutschen Automobil Treuhand GmbH unter www.dat.de unentgeltlich erhältlich ist.
##       baujahr descri
## 1 \n01/2000\n       
## 2 \n07/2000\n       
## 3 \n07/2000\n       
## 4 \n02/2000\n       
## 5 \n05/2000\n       
## 6 \n10/2000\n
# Clean the data and get it into the right format
cars$preis <- gsub("[^0-9.]", "", cars$preis)
cars$ps <- str_extract(cars$ps, "(?<=\\()\\d+(?= PS)")
cars$km <- gsub("[^0-9.]", "", cars$km)
cars$baujahr <- str_extract(cars$baujahr, "(0[1-9]|1[012])[- /.](19|20)\\d\\d")
cars$hubraum <- gsub("[^0-9.]", "", cars$hubraum)
cars$co2 <- substr(cars$co2, 2, 4) 
cars$verbrauch <- str_extract(cars$verbrauch, "\\d+,\\d+ l(?=\\/)")
cars$verbrauch <- str_extract(cars$verbrauch, "\\d+,\\d+")
cars$fahrzeughalter <- gsub("[^0-9.]", "", cars$fahrzeughalter)
cars$kraftstoff <- str_replace_all(cars$kraftstoff, "[\r\n]" , "")
cars$getriebe <- str_replace_all(cars$getriebe, "[\r\n]" , "")
#remove "baujahr" as it is represents the same as "zulassung"
cars$baujahr <- NULL

clean_cars <- cars
clean_cars$preis <- sub("\\.", "", clean_cars$preis)
clean_cars$preis <- as.numeric(clean_cars$preis)
clean_cars$zulassung<- as.numeric(clean_cars$zulassung)
clean_cars$tueren <- as.numeric(clean_cars$tueren)
clean_cars$hubraum <- sub("\\.", "", clean_cars$hubraum)
clean_cars$hubraum <- as.numeric(clean_cars$hubraum)
clean_cars$sitzplätze <- as.numeric(clean_cars$sitzplätze)
clean_cars$ps <- as.numeric(clean_cars$ps)
clean_cars$km <- sub("\\.", "", clean_cars$km)
clean_cars$km <- as.numeric(clean_cars$km)
clean_cars$co2 <- as.numeric(clean_cars$co2)
clean_cars$verbrauch <- as.numeric(gsub(",", ".", gsub("\\.", "", clean_cars$verbrauch)))
clean_cars$fahrzeughalter <- as.numeric(clean_cars$fahrzeughalter)
head(clean_cars)
##              name      marke modell preis karosserie   zustand zulassung
## 1      Opel Corsa       Opel  Corsa   299  Limousine Gebraucht      2000
## 2     Ford Fiesta       Ford Fiesta   499 Kleinwagen Gebraucht      2000
## 3       Mazda 323      Mazda    323   650  Limousine Gebraucht      2000
## 4  Renault Scenic    Renault Scenic   950      Kombi Gebraucht      2000
## 5         Audi A3       Audi     A3   950  Limousine Gebraucht      2000
## 6 Volkswagen Golf Volkswagen   Golf   999  Limousine Gebraucht      2000
##     farbe tueren hubraum sitzplätze fahrzeughalter       getriebe  ps     km
## 1    Blau      2    1199          5              3 Schaltgetriebe  65 126000
## 2    Blau      3    1242          5              3 Schaltgetriebe  75 189137
## 3     Rot      5    1489         NA              2 Schaltgetriebe  88 168000
## 4     Rot      4    1598          5             NA Schaltgetriebe 107 175778
## 5  Silber      5    1595          5              3 Schaltgetriebe 101 230800
## 6 Schwarz      3    1390          5             NA Schaltgetriebe  75 245000
##   kraftstoff co2 verbrauch descri
## 1     Benzin 151       6.3       
## 2     Benzin  NA        NA       
## 3     Benzin  NA        NA       
## 4     Benzin 180       9.6       
## 5     Benzin 187       7.8       
## 6     Benzin 158       6.6
summary(clean_cars)
##      name              marke              modell              preis       
##  Length:57341       Length:57341       Length:57341       Min.   :     1  
##  Class :character   Class :character   Class :character   1st Qu.:  5500  
##  Mode  :character   Mode  :character   Mode  :character   Median :  9950  
##                                                           Mean   : 16421  
##                                                           3rd Qu.: 18890  
##                                                           Max.   :465000  
##                                                           NA's   :1467    
##   karosserie          zustand            zulassung       farbe          
##  Length:57341       Length:57341       Min.   :1996   Length:57341      
##  Class :character   Class :character   1st Qu.:2010   Class :character  
##  Mode  :character   Mode  :character   Median :2014   Mode  :character  
##                                        Mean   :2014                     
##                                        3rd Qu.:2018                     
##                                        Max.   :2021                     
##                                        NA's   :16                       
##      tueren         hubraum        sitzplätze     fahrzeughalter  
##  Min.   :2.000   Min.   :    0   Min.   : 0.000   Min.   :     1  
##  1st Qu.:4.000   1st Qu.: 1242   1st Qu.: 5.000   1st Qu.:     1  
##  Median :4.000   Median : 1595   Median : 5.000   Median :     1  
##  Mean   :4.141   Mean   : 1737   Mean   : 4.759   Mean   :  1292  
##  3rd Qu.:5.000   3rd Qu.: 1991   3rd Qu.: 5.000   3rd Qu.:     2  
##  Max.   :7.000   Max.   :12809   Max.   :55.000   Max.   :122020  
##  NA's   :803     NA's   :1619    NA's   :2379     NA's   :11934   
##    getriebe               ps              km          kraftstoff       
##  Length:57341       Min.   :  5.0   Min.   :     0   Length:57341      
##  Class :character   1st Qu.: 90.0   1st Qu.: 31943   Class :character  
##  Mode  :character   Median :120.0   Median : 81400   Mode  :character  
##                     Mean   :146.5   Mean   : 95674                     
##                     3rd Qu.:163.0   3rd Qu.:141981                     
##                     Max.   :886.0   Max.   :999999                     
##                     NA's   :885     NA's   :31                         
##       co2           verbrauch         descri         
##  Min.   :  0.00   Min.   : 0.200   Length:57341      
##  1st Qu.: 19.00   1st Qu.: 4.700   Class :character  
##  Median : 38.00   Median : 5.500   Mode  :character  
##  Mean   : 54.09   Mean   : 5.912                     
##  3rd Qu.: 72.00   3rd Qu.: 6.600                     
##  Max.   :475.00   Max.   :31.100                     
##  NA's   :8387     NA's   :10584
# check which variables got how many NAs
colSums(is.na(clean_cars))
##           name          marke         modell          preis     karosserie 
##              4             16            702           1467             65 
##        zustand      zulassung          farbe         tueren        hubraum 
##              4             16            162            803           1619 
##     sitzplätze fahrzeughalter       getriebe             ps             km 
##           2379          11934             12            885             31 
##     kraftstoff            co2      verbrauch         descri 
##             12           8387          10584             19
# remove  rows with NAs, but for now delete only entries which are useless if they are NA. If some entries must have no NA values later on, they will get removed. But for now I want to keep as many data as possible.
clean_cars <- clean_cars[complete.cases(clean_cars$name), ]
clean_cars <- clean_cars[complete.cases(clean_cars$preis), ]
clean_cars <- clean_cars[complete.cases(clean_cars$ps), ]

# We have to keep in mind that not all missing values are automatically NA. Some values also could be a string with zero lenght, but if needed, they get removed later on.

Understand the data with different visualisations: Now with removed outliers

Here some outliers get removed.Most of them got detected with the following visualisations. But to have a nice look on the data without outliers I remove them already at the start.

clean_cars <- clean_cars %>%
  filter(sitzplätze < 10) %>%
  filter(fahrzeughalter < 20) %>%
  filter(hubraum < 8000) %>%
  filter(km < 800000) %>%
  filter(verbrauch < 25) %>%
  filter(tueren < 6) %>%
  filter(str_detect(kraftstoff, 'Benzin|Diesel|Elektro|Erdgas|Autogas')) %>%
  filter(str_detect(karosserie, 'Limousine|Kleinwagen|Kombi|Coupé|Cabrio|Van/Kleinbus|SUV/Geländewagen/Pickup|Kombi/Van')) %>%
  filter(str_detect(zustand, 'Gebraucht|Jahreswagen|Neu'))

Now let’s have a first look how the different variables are distributed in the dataset. You can see, that many variables like “preis”, “ps” or “km” are right-scewed (nicer visualisations come below).

par(mfrow=c(2,3))
hist(clean_cars$preis, col = "blue", breaks = 40)
hist(clean_cars$ps, col = "blue", breaks = 40)
hist(clean_cars$km, col = "blue", breaks = 40)
hist(clean_cars$fahrzeughalter, col = "blue", breaks = 40)
hist(clean_cars$zulassung, col = "blue", breaks = 40)
hist(clean_cars$verbrauch, col = "blue", breaks = 40)

par(mfrow=c(1,3))
hist(clean_cars$hubraum, col = "blue", breaks = 40)
hist(clean_cars$tueren, col = "blue", breaks = 40)
hist(clean_cars$sitzplätze, col = "blue", breaks = 40)

clean_cars %>%
  ggplot(aes(x=kraftstoff,y=preis,fill=kraftstoff))+
    geom_boxplot(show.legend = FALSE)+
    stat_summary(fun="mean",show.legend = FALSE)+
    labs(title = 'Der Preis eines Autos',
         subtitle = 'bezogen auf den Kraftstoff',
         x= 'Kraftstoff',
         y='Preis')

This plot shows which fuel type makes a car expensive or cheaper. “Elektro/Diesel” cars seem to be most expensive, but “Benzin” cars for example have many outliers based on the price.

clean_cars %>%
  filter(km < 500000) %>%
  ggplot(aes(x=km,fill=kraftstoff))+
  geom_density(alpha = 0.5)+
  labs(title = 'Wie viele Kilometer fahren Autos',
       subtitle = 'je nach Kraftstoff',
       x= 'Anzahl Kilometer',
       y='')

This plot shows which fuel type reaches how many kilometers. Electric cars haven’t got much kilometers.The reason for this could be that electric cars are newer. “Diesel” and “Autogas” cars have the most kilometers on the tacho.

clean_cars%>%
  group_by(zulassung)%>%
  count()%>%
  ggplot()+geom_col(aes(y=n,x=zulassung))+
  labs(title = 'Wie viele Autos sind für jedes Jahr enthalten',
       x= 'Jahr der Zulassung',
       y='Anzahl an Autos')

This plot shows how many cars for each year are in the data set. Normally an even distribution would be expected, because the webscrape algorithm should scrape the same amount of data for every year. But during scraping I got many disonnects and the scraping interrupted. This is the reason why every year got a different amount of cars.

clean_cars%>%
  group_by(marke)%>%
  count()%>%
  arrange(desc(n))%>%
  filter(n>90)%>%
  ggplot()+geom_col(aes(x=n,y=reorder(marke,n),fill=marke),show.legend = FALSE)+
  geom_label(aes(y = reorder(marke,n), x = n, label = paste(round((n/sum(n))*100,2),'%')))+
  labs(title = 'Wie viele Autos pro Marke sind im Datensatz',
       subtitle = '',
       x= 'Prozent',
       y='Marke')

This plot shows which car brands are in the dataset and how many of them.It makes sense that most of the cars are from makes like “Volkswagen” until “Citroen” because the scrape algorithm mainly focused on these 13 makes.I choose these car brands because they were listed under “Top Marken” on “autoscout24.de”.

imp_cars <- clean_cars %>%
  filter(str_detect(marke, 'BMW|Audi|Citroen|Fiat|Ford|Hyundai|Kia|Mercedes-Benz|Nissan|Opel|Peugeot|Porsche|Renault|SEAT|Skoda|smart|Suzuki|Volkswagen|Volvo'))
grid.arrange(
  ggplot(imp_cars, aes(reorder(marke, preis, median), preis))+
    geom_boxplot()+geom_jitter(alpha=0.1)+geom_hline(aes(yintercept=median(preis)))+
    scale_y_log10()+coord_flip()+xlab("Marke ordered by median Price"))

This plot shows the median price of the different car brands. It can be seen that “Porsche” cars are one of the most expensive cars in the datset. It also can be seen, that most of the cars cost around 10000 Euros. The black line shows the median at 9900 Euros.

Now check what variables might have an influence on the car price.

In most of the boxplots, there are many outliers. This could be a sign that the data isn’t normal distributed.

clean_cars %>%
  ggplot(aes(x=karosserie,y=preis,fill=karosserie))+
  geom_boxplot(show.legend = FALSE)+
  stat_summary(fun="mean",show.legend = FALSE)+
  labs(title = 'Der Preis eines Autos',
       subtitle = 'bezogen auf den Fahrzeugtypen',
       x= 'Karosserie',
       y='Preis')

Filtered out cars like “Pritsche” or “Viehtransporter” because these aren’t the cars I want to predict. “Coupés” tend to be more expensive than for example “Kleinwagen”. But also “Cabrios” and “Geländewagen” show many outliers to the top. But this plot shows in general that the car body type could have an influence on the price.

clean_cars %>%
  ggplot(aes(x=zustand,y=preis,fill=zustand))+
  geom_boxplot(show.legend = FALSE)+
  stat_summary(fun="mean",show.legend = FALSE)+
  labs(title = 'Der Preis eines Autos',
       subtitle = 'bezogen auf den Zustand',
       x= 'Zustand',
       y='Preis')

I am only interested in new and used cars, so i am filtering out “Tageszulassung” and “Vorführfahrzeug”. “Jahreswagen” tend to be more expensive than “Gebraucht”. This makes sense because “Jahreswagen” just count as “Jahreswagen” for 12 months after the cars approval. This supports the thesis that newer cars tend to be more expensive than older cars.

clean_cars %>%
  ggplot(aes(x=farbe,y=preis,fill=farbe))+
  geom_boxplot(show.legend = FALSE)+
  stat_summary(fun="mean",show.legend = FALSE)+
  labs(title = 'Der Preis eines Autos',
       subtitle = 'bezogen auf die Farbe',
       x= 'Farbe',
       y='Preis')

Out of this plot I would say that there is no clear trend. It shows that every color has low priced cars but also outliers which represent high priced cars. With this visualisation it could be said that the color of a car has not too much influence on the price.

par(mar = c(5, 4, 3, 8),xpd = TRUE)
plot(clean_cars$tueren, clean_cars$preis, main="Türen-Preis",
     xlab="Türen", ylab="Preis", pch=19,cex=0.8, col=factor(clean_cars$karosserie))
legend("topright",
       inset = c(- 0.42, -0.15),
       legend = levels(factor(clean_cars$karosserie)),
       pch = 19,
       cex= 0.6,
       box.lty=0,
       col = factor(levels(factor(clean_cars$karosserie))))

Not too much price differences between numbers of doors. But cars with two doors are the mostly the expensive ones. One reason for this is that sports cars often just have two doors (like Coupés and Cabrios). Kombis, Limousines and SUVs have got around 4-5 doors.

boxplot(preis~sitzplätze, data = clean_cars)

boxplot(preis~fahrzeughalter, data = clean_cars)

The less number of owners the higher is the price. So the number of car owners can have an influence on the car price.

hist(clean_cars$hubraum)

plot(clean_cars$hubraum, clean_cars$preis, main="Hubraum-Preis",
     xlab="Hubraum", ylab="Preis", pch=19)

Here it can be seen that the engine size from most of the cars is from 1000 to 2000 cubic meters. The graph is also right scewed. But the plot shows that the larger the cars engine the higher is the price of the car. In a correlation plot later on you can see that the engine size correlates strong with the horsepower of a car.

clean_cars %>%
  filter(str_detect(getriebe, 'Automatik|Halbautomatik|Schaltgetriebe')) %>%
  ggplot(aes(x=getriebe,y=preis,fill=getriebe))+
  geom_boxplot(show.legend = FALSE)+
  stat_summary(fun="mean",show.legend = FALSE)+
  labs(title = 'Der Preis eines Autos',
       subtitle = 'bezogen auf das Getriebe',
       x= 'Getriebe',
       y='Preis')

Half automatic cars are the cheapest ones. “Schaltgetriebe” cars got many outliers to the top. Many sport cars got “Wippschalter”, which could be a reason for the high priced “Schaltgetriebe” cars. But automatic cars tend to be more expensive in general.

par(mar = c(5, 4, 4, 8),xpd = TRUE)
plot(clean_cars$ps, clean_cars$preis, main="Ps-Preis",
     xlab="ps", ylab="Preis", pch=19,cex=0.5, col=factor(clean_cars$karosserie))
legend("topright",
       inset = c(- 0.42, -0.05),
       legend = levels(factor(clean_cars$karosserie)),
       pch = 19,
       cex= 0.8,
       box.lty=0,
       col = factor(levels(factor(clean_cars$karosserie))))

Here you can see that this scatterplot is mixed. To maybe get a better insight I use the fuel type as group type:

par(mar = c(5, 4, 3, 8),xpd = TRUE)
v <- clean_cars %>%
  filter(str_detect(kraftstoff, 'Benzin|Diesel|Elektro|Erdgas|Autogas'))
plot(v$ps, v$preis, main="Ps-Preis",
     xlab="ps", ylab="Preis", pch=19,cex=0.5, col=factor(v$kraftstoff))
legend("topright",
       inset = c(- 0.22, -0.05),
       legend = levels(factor(v$kraftstoff)),
       pch = 19,
       cex= 0.6,
       box.lty=0,
       col = factor(levels(factor(v$kraftstoff))))

Trend: the more ps, the higher the price. In this plot you can see that the cars which got many ps and high prices are mostly petrol cars or petrol/electric hybrids. Diesel cars go to around 400ps and 100.000 Euros and below.

par(mar = c(5, 4, 3, 8),xpd = TRUE)
plot(clean_cars$km, clean_cars$preis, main="Km-Preis",
     xlab="km", ylab="Preis",cex=0.5, pch=19, col=factor(v$kraftstoff))
legend("topright",
       inset = c(- 0.22, -0.05),
       legend = levels(factor(v$kraftstoff)),
       pch = 19,
       cex= 0.6,
       box.lty=0,
       col = factor(levels(factor(v$kraftstoff))))

Trend: the less kilometers, the higher the price. It shows that Diesel cars got the most kilometers on the tacho. It can also be seen that the very high priced petrol cars got just a few kilometers on the tacho. A reason for this could be that the loss of value gets even higher for super sport cars with every kilometer they drive. In total the graph shows a big price decrease with every more kilometer driven. So it shows that the number of driven kilometers haves an influence on the car price.

par(mar = c(5, 4, 3, 8),xpd = TRUE)
plot(clean_cars$verbrauch, clean_cars$preis, main="Verbrauch-Preis",
     xlab="Verbrauch in l", ylab="Preis",cex=0.5, pch=19, col=factor(v$kraftstoff))
legend("topright",
       inset = c(- 0.22, -0.05),
       legend = levels(factor(v$kraftstoff)),
       pch = 19,
       cex= 0.6,
       box.lty=0,
       col = factor(levels(factor(v$kraftstoff))))

Electric cars got the lowest consumption, followed by Diesel cars. Petrol and some Autogas cars got the highest consumption.

clean_cars %>%
  ggplot(aes(zulassung, preis))+
  geom_boxplot(aes(group=zulassung))+
  geom_jitter(alpha=0.1)+geom_smooth(method="loess")+
  scale_y_log10()
## `geom_smooth()` using formula 'y ~ x'

This overview shows, that newer cars tend to be more expensive. Just some old cars which are older than 20 years doesn’t fit perfectely to the pattern.

Look now at the correlations between some variables:

# Convert "zulassung" into the age of a car:
clean_cars %>% mutate(Alter = 2021-zulassung) -> clean_cars
clean_cars %>% 
  select(preis, Alter, km, hubraum, ps, sitzplätze, verbrauch,co2) %>%
  cor() %>% 
  ggcorrplot(lab=TRUE)

#correlation Analysis
clean_cars[sapply(clean_cars, is.character)] <- lapply(clean_cars[sapply(clean_cars, is.character)], 
                                       as.factor)
numericData <- clean_cars[,sapply(clean_cars, is.numeric)] #filter all numeric vars
corMat <- cor(numericData)
corrplot(corMat, method = "number", type = "lower")

highlyCorrelated <- findCorrelation(corMat, cutoff = 0.6) 
highlyCorCol <- colnames(numericData)[highlyCorrelated]
highlyCorCol
## [1] "Alter"     "zulassung" "verbrauch" "preis"     "hubraum"

Correlation between: km-Alter; ps-preis; hubraum-ps; ps-verbrauch; verbrauch-hubraum But: ps correlates more to the price than hubraum

Detect outliers

Have a look on some of the outliers which got detected by the different visualisations.

The most expensive cars in the dataset: - it can be seen that the most expensive cars don’t have to be the newest cars. The “BMW Z8” for example is a very high priced car from the early two thousands. The car is probably rare in these conditions (not too much kilometers on the tacho).

pr <- clean_cars %>%
  filter(preis > 200000)
pr[ , -which(names(pr) %in% c("descri"))]
##                      name         marke   modell  preis              karosserie
## 1                  BMW Z8           BMW       Z8 210000                  Cabrio
## 2                  BMW Z8           BMW       Z8 239888                  Cabrio
## 3                  BMW Z8           BMW       Z8 298888                  Cabrio
## 4             Porsche 997       Porsche      997 400000                   Coupé
## 5       Mercedes-Benz SLS Mercedes-Benz      SLS 209990                   Coupé
## 6       Mercedes-Benz SLS Mercedes-Benz      SLS 220000                   Coupé
## 7     Mercedes-Benz G 280 Mercedes-Benz    G 280 249000 SUV/Geländewagen/Pickup
## 8       Mercedes-Benz SLS Mercedes-Benz      SLS 229000                   Coupé
## 9             Porsche 991       Porsche      991 349900                  Cabrio
## 10            Porsche 997       Porsche      997 400000                   Coupé
## 11            Porsche 997       Porsche      997 275000                   Coupé
## 12            Porsche 997       Porsche      997 359900                   Coupé
## 13            Porsche 997       Porsche      997 389500                   Coupé
## 14      Mercedes-Benz SLS Mercedes-Benz      SLS 220000                   Coupé
## 15    Mercedes-Benz G 280 Mercedes-Benz    G 280 249000 SUV/Geländewagen/Pickup
## 16      Mercedes-Benz SLS Mercedes-Benz      SLS 209000                   Coupé
## 17            Porsche 997       Porsche      997 268800                  Cabrio
## 18            Porsche 997       Porsche      997 299000                  Cabrio
## 19            Porsche 911       Porsche      911 335000                  Cabrio
## 20            Porsche 997       Porsche      997 399000                  Cabrio
## 21    Mercedes-Benz G 500 Mercedes-Benz    G 500 356980                  Cabrio
## 22            Porsche 997       Porsche      997 374900                   Coupé
## 23      Mercedes-Benz SLS Mercedes-Benz      SLS 279900                  Cabrio
## 24                Audi R8          Audi       R8 295000                   Coupé
## 25      Mercedes-Benz SLS Mercedes-Benz      SLS 460000                   Coupé
## 26 Mercedes-Benz G 63 AMG Mercedes-Benz G 63 AMG 279000 SUV/Geländewagen/Pickup
## 27            Porsche 991       Porsche      991 289900                   Coupé
## 28            Porsche 992       Porsche      992 222000                   Coupé
## 29             Audi RS Q8          Audi    RS Q8 249000 SUV/Geländewagen/Pickup
## 30             Audi RS Q8          Audi    RS Q8 249900 SUV/Geländewagen/Pickup
## 31             Audi RS Q8          Audi    RS Q8 249900 SUV/Geländewagen/Pickup
## 32             Audi RS Q8          Audi    RS Q8 269900 SUV/Geländewagen/Pickup
## 33               Audi RS6          Audi      RS6 289900                   Kombi
## 34 Mercedes-Benz S 65 AMG Mercedes-Benz S 65 AMG 289900               Limousine
##      zustand zulassung   farbe tueren hubraum sitzplätze fahrzeughalter
## 1  Gebraucht      2000 Schwarz      2    4941          2              3
## 2  Gebraucht      2001 Schwarz      2    4941          2              2
## 3  Gebraucht      2002  Silber      2    4941          2              3
## 4  Gebraucht      2010    Weiß      2    3600          2              1
## 5  Gebraucht      2011  Silber      2    6208          2              2
## 6  Gebraucht      2011     Rot      2    6208          2              1
## 7  Gebraucht      2011 Schwarz      5    2987          4              1
## 8  Gebraucht      2010    Weiß      2    6208          2              2
## 9  Gebraucht      2020    Grau      2    3996          4              1
## 10 Gebraucht      2010    Weiß      2    3600          2              1
## 11 Gebraucht      2010 Schwarz      2    3600          2              2
## 12 Gebraucht      2010    Grau      2    3800          4              2
## 13 Gebraucht      2010 Schwarz      2    3600          2              1
## 14 Gebraucht      2011     Rot      2    6208          2              1
## 15 Gebraucht      2011 Schwarz      5    2987          4              1
## 16 Gebraucht      2011    Grau      2    6208          2              2
## 17 Gebraucht      2011    Weiß      2    3800          2              1
## 18 Gebraucht      2011    Blau      2    3800          2              1
## 19 Gebraucht      2011    Weiß      2    3800          2              1
## 20 Gebraucht      2011 Schwarz      2    3800          2              1
## 21 Gebraucht      2012    Grau      3    5461          4              2
## 22 Gebraucht      2012    Weiß      2    3996          2              2
## 23 Gebraucht      2013     Rot      2    6208          2              1
## 24 Gebraucht      2013 Schwarz      2    5204          2              2
## 25 Gebraucht      2014    Grau      2    6208          2              1
## 26 Gebraucht      2015    Weiß      5    5461          5              1
## 27 Gebraucht      2017    Gelb      2    3800          4              1
## 28 Gebraucht      2021    Weiß      2    3996          2              1
## 29 Gebraucht      2021 Schwarz      4    3996          5              1
## 30 Gebraucht      2021 Schwarz      4    3996          5              1
## 31 Gebraucht      2021 Schwarz      4    3996          5              1
## 32 Gebraucht      2021 Schwarz      4    3996          5              1
## 33 Gebraucht      2021 Schwarz      4    3996          5              1
## 34 Gebraucht      2020 Schwarz      4    5980          4              2
##          getriebe  ps    km kraftstoff co2 verbrauch Alter
## 1  Schaltgetriebe 400 39600     Benzin 349      14.5    21
## 2  Schaltgetriebe 400 41200     Benzin 349      14.5    20
## 3       Automatik 381 67000     Benzin 349      14.5    19
## 4  Schaltgetriebe 620  2275     Benzin 284      11.9    11
## 5       Automatik 571 17900     Benzin 308      13.2    10
## 6       Automatik 571 14845     Benzin 308      13.2    10
## 7       Automatik 184   819     Diesel 320      12.2    10
## 8       Automatik 571  8500     Benzin   8      13.2    11
## 9  Schaltgetriebe 510  4250     Benzin  17      13.8     1
## 10 Schaltgetriebe 620  2275     Benzin  84      11.9    11
## 11 Schaltgetriebe 620 41394     Benzin  82      11.9    11
## 12 Schaltgetriebe 408 42850     Benzin  51      10.6    11
## 13 Schaltgetriebe 620  5500     Benzin  84      11.9    11
## 14      Automatik 571 14845     Benzin   8      13.2    10
## 15      Automatik 184   819     Diesel  20      12.2    10
## 16      Automatik 571 21000     Benzin   8      13.2    10
## 17      Automatik 408  1435     Benzin  42      10.3    10
## 18      Automatik 408 10200     Benzin  42      10.3    10
## 19      Automatik 408   110     Benzin  42      10.3    10
## 20      Automatik 408  1408     Benzin  42      10.3    10
## 21      Automatik 387 24972     Benzin  48      14.9     9
## 22 Schaltgetriebe 500 11700     Benzin  27      13.8     9
## 23      Automatik 591  8500     Benzin  13      13.2     8
## 24      Automatik 799 11000     Benzin  46      14.9     8
## 25      Automatik 631 17635     Benzin  21      13.7     7
## 26      Automatik 544  2121     Benzin  22      13.8     6
## 27      Automatik 606  4158     Benzin  12       9.1     4
## 28      Automatik 510  2490     Benzin  83      12.4     0
## 29      Automatik 740  2200     Benzin  77      12.1     0
## 30      Automatik 740  7900     Benzin  76      12.1     0
## 31      Automatik 740  7900     Benzin  76      12.1     0
## 32      Automatik 740  1050     Benzin  76      12.1     0
## 33      Automatik 799  1050     Benzin  65      11.6     0
## 34      Automatik 630 16343     Benzin  25      14.2     1

The cars with the most driven kilometers:

pr1 <- clean_cars %>%
  filter(km > 500000)
pr1[ , -which(names(pr1) %in% c("descri"))]
##                       name         marke       modell preis   karosserie
## 1      Mercedes-Benz E 200 Mercedes-Benz        E 200  2990    Limousine
## 2  Volkswagen T5 Caravelle    Volkswagen T5 Caravelle  7480 Van/Kleinbus
## 3      Mercedes-Benz E 220 Mercedes-Benz        E 220  5400        Kombi
## 4       Mercedes-Benz Vito Mercedes-Benz         Vito  7300        Kombi
## 5      Mercedes-Benz C 220 Mercedes-Benz        C 220  4899        Kombi
## 6                  BMW 320           BMW          320  7800    Limousine
## 7      Mercedes-Benz E 200 Mercedes-Benz        E 200  5899    Limousine
## 8       Mercedes-Benz Vito Mercedes-Benz         Vito  7900 Van/Kleinbus
## 9               SEAT Ibiza          SEAT        Ibiza  8000    Limousine
## 10                Fiat 500          Fiat          500  6950    Limousine
## 11             Ford Galaxy          Ford       Galaxy  1200        Kombi
##      zustand zulassung   farbe tueren hubraum sitzplätze fahrzeughalter
## 1  Gebraucht      2004  Silber      4    2148          5              3
## 2  Gebraucht      2007    Grau      4    1896          9              2
## 3  Gebraucht      2010    Weiß      5    2143          5              2
## 4  Gebraucht      2011 Schwarz      4    2143          9              2
## 5  Gebraucht      2012 Schwarz      5    2143          5              2
## 6  Gebraucht      2012 Schwarz      4    1995          5              3
## 7  Gebraucht      2013   Beige      4    2143          5              1
## 8  Gebraucht      2014  Silber      4    2143          3              1
## 9  Gebraucht      2014    Grün      3    1390          5              1
## 10 Gebraucht      2014    Blau      3    1242          4              2
## 11 Gebraucht      2005     Rot      5    1896          5              2
##          getriebe  ps     km kraftstoff co2 verbrauch Alter
## 1  Schaltgetriebe 122 543000     Diesel 162       6.1    17
## 2  Schaltgetriebe 102 588000     Diesel 224       8.5    14
## 3       Automatik 170 696000     Diesel  63       6.2    11
## 4       Automatik 136 645500     Diesel  96       7.4    10
## 5       Automatik 170 527205     Diesel  62       6.1     9
## 6  Schaltgetriebe 184 501711     Diesel  19       4.5     9
## 7       Automatik 136 530000     Diesel  27       4.8     8
## 8  Schaltgetriebe 163 620000     Diesel  96       7.4     7
## 9  Schaltgetriebe  86 750000     Benzin  39       5.9     7
## 10 Schaltgetriebe  69 636560     Benzin  17       5.1     7
## 11 Schaltgetriebe  90 557000     Diesel  81       6.7    16

The car with the most kilometers got 999999km. As it is on the road since 2001, it could well be that this car has got this much kilometers (50000km per year is realistic). In general it makes sense that most of the cars with many kilometers are older cars.

Transforming Varibales to maybe get other insigths

As one of the last tasks for this data understanding sheet, I want to have a look on the “descri” column, which represents the cars description. As not every car has got a description included, i just get the cars with a description.

# How many cars got descriptions:
descriptions<- clean_cars %>%
  filter(descri != "")
tescht <- descriptions %>%
  filter(preis > 50000)%>%
  summarise(descri=paste(descri,collapse=''))
tescht1 <- descriptions %>%
  filter(preis < 50000)%>%
  summarise(descri=paste(descri,collapse=''))

first_corpus = Corpus(VectorSource(tescht$descri))
first_tdm = TermDocumentMatrix(
  first_corpus,
  control = list(
    removePunctuation=TRUE,
    stopwords = stopwords("de"),
    removeNumbers= TRUE, tolower = TRUE
  )
)
first_m = as.matrix(first_tdm)
sec_corpus = Corpus(VectorSource(tescht1$descri))
sec_tdm = TermDocumentMatrix(
  sec_corpus,
  control = list(
    removePunctuation=TRUE,
    stopwords = stopwords("de"),
    removeNumbers= TRUE, tolower = TRUE
  )
)
sec_m = as.matrix(sec_tdm)
# LOOK AT MEANINGFUL WORDS FOR HIGH PRICED CARS
sort(rowSums(first_m),decreasing=T)[1:10]
##    porsche     f<fc>r       inkl   anzeigen       vorn       plus    schwarz 
##       3471       3394       3088       2641       2228       2082       1996 
## management     hinten       mehr 
##       1543       1522       1347
# Create Wordclouds
lux_word_freqs = sort(rowSums(first_m), decreasing = TRUE)
nor_word_freqs = sort(rowSums(sec_m), decreasing = TRUE)
#create a data.frame with words and their frequencies
lux_dm = data.frame(word = names(lux_word_freqs), freq = lux_word_freqs)
nor_dm = data.frame(word = names(nor_word_freqs), freq = nor_word_freqs)
Encoding(lux_dm$word) <- "ISO-8859-1"
Encoding(nor_dm$word) <- "ISO-8859-1"
color_lux = c("#fa6604","#04faee","#9304fa")
color_nor =  c("#f2dadb","#e810d2","#e81010")
#This is the wordcloud for luxury cars (above 50000 Euros)
wordcloud2(lux_dm, color = rep_len(color_lux,100), fontFamily = "Abel", rotateRatio = 0)

I am not sure if it makes too much sense that the cut was made at 50000 Euros. The wordcloud shows some intersting words like “Porsche” for luxury cars, but many words from cars below 50000 are the same. This makes sense in a way because it does not mean that a car has no qualities just because the price is below 50000 Euros. These cars could also have luxury equipments.

#This is the wordcloud for "normal", middle class cars (below 50000 Euros)
wordcloud2(nor_dm, color = rep_len(color_nor,100), fontFamily = "Abel", rotateRatio = 0)
#Problem: Which words for normal cars?
normal_words <- wordcloud2(nor_dm, color = rep_len(color_nor,100), fontFamily = "Abel", rotateRatio = 0)
print(normal_words)

include_graphics("cloud_norm1.png")